package controller;

import cn.edu.zut.model.Book;
import cn.edu.zut.model.BorrowBook;
import cn.edu.zut.model.Reader;
import cn.edu.zut.service.BookService;
import cn.edu.zut.service.BorrowBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@Controller
public class BorrowBookController {
    @Autowired
    BorrowBookService borrowBookService;
    @Autowired
    BorrowBook borrowBookGlobal;
    @Autowired
    BookService bookService;
    @Autowired
    Book book;
    int noRecord=0;
    List<Integer> bookIdList=new ArrayList<>();

    @RequestMapping(value="/borrowBook")
    public String borrowBook(){
        return "/admin/borrowbook/borrowLeft";
    }
    @RequestMapping(value="/borrowBookRecordInit")
    public String borrowBookRecord(){
        return "/admin/borrowbook/record";
    }
    @RequestMapping(value="/searchById",method= RequestMethod.GET)
    public ModelAndView searchRecord(HttpServletRequest request) throws ParseException {
        String readerId=request.getParameter("id");
        Reader reader=borrowBookService.selectReaderByReaderId(readerId);
        List<BorrowBook> borrowBooks=borrowBookService.selectBorrowBookInfo(readerId);
        ModelAndView modelAndView=new ModelAndView();
//        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
//        for (BorrowBook borrowBook:borrowBooks
//             ) {
//            //格式化借书日期
//            String bd=simpleDateFormat.format(borrowBook.getBorrowDate());
//            Date BorrowDate=simpleDateFormat.parse(bd);
//            borrowBook.setBorrowDate(BorrowDate);
//
//            //格式化应还日期
//            String sr=simpleDateFormat.format(borrowBook.getShouldReturn());
//            Date shouldReturn=simpleDateFormat.parse(sr);
//            borrowBook.setShouldReturn(shouldReturn);
//
//            //格式化返还日期
//            if (borrowBook.getReturnDate()!=null){
//                String rd=simpleDateFormat.format(borrowBook.getReturnDate());
//                Date returnDate=simpleDateFormat.parse(rd);
//                borrowBook.setReturnDate(returnDate);
//            }
//            else
//            { borrowBook.setReturnDate(null);}
//        }
            if (borrowBooks.isEmpty()){
                noRecord=1;
                modelAndView.addObject("noRecord",noRecord);
                modelAndView.setViewName("/admin/borrowbook/record");
                return modelAndView;
            }else {
                modelAndView.addObject("borrowBooks",borrowBooks);
                modelAndView.addObject("reader",reader);
                modelAndView.setViewName("/admin/borrowbook/record");
                return modelAndView;
            }
    }
    @RequestMapping(value="/updateBorrowBook",method = RequestMethod.GET)
    public ModelAndView updateBorrowBookRecord(HttpServletRequest request,HttpSession session) throws ParseException {
        List<BorrowBook> borrowBooks = borrowBookService.selectBorrowBookInfo(request.getParameter("id"));
        Reader reader=borrowBookService.selectReaderByReaderId(request.getParameter("id"));
        int bookid = Integer.valueOf(request.getParameter("bookid"));
        book.setBookid(bookid);
        book.setStatus(0);
        bookService.updateBookStatus(book);
        Calendar calendar=Calendar.getInstance();
        Date date=new Date();
        for (BorrowBook borrowBook : borrowBooks
        ) {
            //标记归还
            if (borrowBook.getBookId() == bookid) {
                //借书日期
                calendar.setTime(borrowBook.getBorrowDate());
                long borrowDate=calendar.getTimeInMillis();
                //归还日期
                calendar.setTime(date);
                long nowDate=calendar.getTimeInMillis();
                long betweenDays=(nowDate-borrowDate)/(1000*24*3600);
                if (reader.getType()==1){   //计算教师的逾期罚款
                    if((betweenDays - 90) > 0){
                        int days= (int) (betweenDays-90);
                        float fine= (float) (0.5*days);
                        borrowBook.setFine(fine);
                    }
                    else {
                        borrowBook.setFine(0);
                    }
                    borrowBookService.deleteBorrowInfo(borrowBook);
                    borrowBook.setReturnDate(date);
                    borrowBookService.updateBorrowInfo(borrowBook);//更新日期
                }
                else if (reader.getType()==2){   //计算学生的逾期罚款
                    if((betweenDays - 60) > 0){
                        int days= (int) (betweenDays-60);
                        float fine= (float) (0.5*days);
                        borrowBook.setFine(fine);
                    }
                    else {
                        borrowBook.setFine(0);
                    }
                }
                borrowBookService.deleteBorrowInfo(borrowBook);
                borrowBook.setReturnDate(date);
                borrowBookService.updateBorrowInfo(borrowBook);//更新日期
            }
        }
        ModelAndView modelAndView = searchRecord(request);
        return modelAndView;
    }
    @RequestMapping(value="/deleteBorrowBook",method = RequestMethod.GET)
    public ModelAndView deleteBorrowBookRecord(HttpServletRequest request){
        List<BorrowBook> borrowBookList=borrowBookService.selectBorrowBookInfo(request.getParameter("id"));
        int bookId=Integer.valueOf(request.getParameter("bookid"));
        if (bookIdList.size()==borrowBookList.size()){
            bookIdList.clear();
        }
        bookIdList.add(bookId);
        Reader reader=borrowBookService.selectReaderByReaderId(request.getParameter("id"));
        List<BorrowBook> borrowBooks=new ArrayList<>();
        for (BorrowBook borrowBook: borrowBookList
        ) {
            if (borrowBook.getFlag()==1){
                if(bookIdList.contains(borrowBook.getBookId())){
                }
                else{
                    borrowBooks.add(borrowBook);
                }
            }
            if (borrowBook.getFlag() == 0) {
                borrowBooks.add(borrowBook);
            } else {
                if(bookIdList.size()==borrowBookList.size()){
                    borrowBooks=null;
                }
            }
        }
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("borrowBooks",borrowBooks);
        modelAndView.addObject("reader",reader);
        modelAndView.setViewName("/admin/borrowbook/record");
        return modelAndView;
    }
    @RequestMapping(value = "/addBorrowBookRecord",method = RequestMethod.GET)
    public String addBorrowBook(){
        return "/admin/borrowbook/insertBorrowBook";
    }
    @RequestMapping(value ="/insertBorrowBook",method = RequestMethod.GET)
    public ModelAndView insertBorrowBook(HttpServletRequest request){
        String readerId=request.getParameter("readerid");
        String bookIdString=request.getParameter("bookid");
        Reader reader=borrowBookService.selectReaderByReaderId(readerId);
        List<BorrowBook> borrowBookList = borrowBookService.selectBorrowBookInfo(request.getParameter("readerid"));
        Map<String,Integer> map=new HashMap<>();
        ModelAndView modelAndView=new ModelAndView();
        int visit=0;
        if ((bookIdString.equals("")) | (readerId.equals(""))){  //判断输入是否为空
            int noId = 1;
            int noUser = 0;
            int borrowNum =0;
            int noBook=0;
            map.put("noId",noId);
            map.put("noUser",noUser);
            map.put("borrowNum",borrowNum);
            map.put("noBook",noBook);
            modelAndView.addAllObjects(map);
            modelAndView.setViewName("/admin/borrowbook/addSituation");
            return modelAndView;
        } else if (reader == null) {    //判断读者是否存在
            int noId = 0;
            int noUser = 1;
            int borrowNum =0;
            int noBook=0;
            map.put("noUser",noUser);
            map.put("noId",noId);
            map.put("borrowNum",borrowNum);
            map.put("noBook",noBook);
            modelAndView.addAllObjects(map);
            modelAndView.setViewName("/admin/borrowbook/addSituation");
            return modelAndView;
        }
        List<Book> books=bookService.selectBookByBookid(Integer.valueOf(bookIdString)); //查找书籍
        if (books.isEmpty() || books.get(0).getStatus()==1){       //判断书籍是否在库
            int noId = 0;
            int noUser = 0;
            int borrowNum =0;
            int noBook=1;
            map.put("noBook",noBook);             //将各种情况的标识放入modelAndView
            map.put("noUser",noUser);
            map.put("noId",noId);

            map.put("borrowNum",borrowNum);
            modelAndView.addAllObjects(map);
            modelAndView.setViewName("/admin/borrowbook/addSituation");
            return modelAndView;
        }
        Date date = new Date();             //自动生成当前借书日期
        Calendar cl = Calendar.getInstance();
        if (reader.getType() == 1) {
            int count =0;
            for (BorrowBook borrowBook : borrowBookList
            ) {
                if (borrowBook.getFlag() == 0) {
                    count++;
                }
            }
            if (count+ 1 <= 10) {      //教师只能借十本
                for (BorrowBook borrowBook:borrowBookList
                ) {
                    if (borrowBook.getBookId()==Integer.valueOf(request.getParameter("bookid"))) {
                        borrowBook.setFlag(0);
                        borrowBook.setBorrowDate(date);
                        cl.setTime(date);
                        cl.add(Calendar.DATE, 90);
                        Date newDate = cl.getTime();
                        borrowBook.setShouldReturn(newDate);
                        borrowBook.setReturnDate(null);
                        borrowBook.setFine(0);
                        book.setStatus(1);             //相应的书籍状态的改为借出
                        book.setBookid(Integer.valueOf(bookIdString));
                        bookService.updateBookStatus(book);
                        borrowBookService.updateBorrowFlag(borrowBook);
                        int noId = 0;
                        int noUser = 0;
                        int borrowNum =0;
                        int noBook=0;
                        map.put("noBook",noBook);
                        map.put("borrowNum",borrowNum);
                        map.put("noUser",noUser);
                        map.put("noId",noId);
                        modelAndView.addAllObjects(map);
                        modelAndView.setViewName("/admin/borrowbook/addSituation");
                        return modelAndView;
                    }
                }
                cl.setTime(date);
                cl.add(Calendar.DATE, 90);
                Date newDate = cl.getTime();
                borrowBookGlobal.setShouldReturn(newDate);
            } else visit=1;
        } else {
            int count =0;
            for (BorrowBook borrowBook : borrowBookList
            ) {
                if (borrowBook.getFlag() == 0) {
                    count++;
                }
            }
            if (count + 1 <= 5) {         //学生只能借5本
                for (BorrowBook borrowBook:borrowBookList
                ) {
                    if (borrowBook.getBookId()==Integer.valueOf(request.getParameter("bookid"))){
                        borrowBook.setFlag(0);
                        borrowBook.setBorrowDate(date);
                        cl.setTime(date);
                        cl.add(Calendar.DATE, 90);
                        Date newDate = cl.getTime();
                        borrowBook.setReturnDate(null);
                        borrowBook.setShouldReturn(newDate);
                        borrowBook.setFine(0);
                        book.setStatus(1);             //相应的书籍状态的改为借出
                        book.setBookid(Integer.valueOf(bookIdString));
                        bookService.updateBookStatus(book);
                        borrowBookService.updateBorrowFlag(borrowBook);
                        int noId = 0;
                        int noUser = 0;
                        int borrowNum =0;
                        int noBook=0;
                        map.put("noBook",noBook);
                        map.put("noId",noId);
                        map.put("borrowNum",borrowNum);
                        map.put("noUser",noUser);
                        modelAndView.addAllObjects(map);
                        modelAndView.setViewName("/admin/borrowbook/addSituation");
                        return modelAndView;
                    }
                }
                cl.setTime(date);
                cl.add(Calendar.DATE, 60);
                Date newDate = cl.getTime();
                borrowBookGlobal.setShouldReturn(newDate);
            } else visit = 1;
        }
        if (1 == visit){
            int noId = 0;
            int noUser = 0;
            int borrowNum =1;
            int noBook=0;
            map.put("borrowNum",borrowNum);
            map.put("noBook",noBook);
            map.put("noUser",noUser);
            map.put("noId",noId);
            modelAndView.addAllObjects(map);
            modelAndView.setViewName("/admin/borrowbook/addSituation");
            return modelAndView;
        }
        book.setStatus(1);             //相应的书籍状态的改为借出
        book.setBookid(Integer.valueOf(bookIdString));
        bookService.updateBookStatus(book);
        borrowBookGlobal.setReaderId(readerId);
        borrowBookGlobal.setBookId(Integer.valueOf(request.getParameter("bookid")));
        borrowBookGlobal.setBorrowDate(date);
        borrowBookGlobal.setReturnDate(null);
        borrowBookGlobal.setFine(0);
        borrowBookService.insertBorrowerInfo(borrowBookGlobal);

        int borrowNum =0;
        int noBook=0;
        int noId = 0;
        int noUser = 0;

        map.put("noId",noId);
        map.put("noBook",noBook);
        map.put("borrowNum",borrowNum);
        map.put("noUser",noUser);
        modelAndView.addAllObjects(map);
        modelAndView.setViewName("/admin/borrowbook/addSituation");
        return modelAndView;
    }
}
